package com.web;

import com.mysql.cj.Session;
import com.pojo.user;
import com.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(value = "/servletLogin")
public class servletLogin extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        UserService us = new UserService();

        user u = us.login(name, password);
        System.out.println(name);
        System.out.println(password);
        if(u!=null)
        {
            if("1".equals(remember)){
                //创建cookie
                Cookie cook = new Cookie("name",name);
                Cookie cook2 = new Cookie("password",password);

                cook.setMaxAge(60 * 60 * 24 * 7);
                cook2.setMaxAge(60 * 60 * 24 * 7);

                res.addCookie(cook);
                res.addCookie(cook2);
            }

            //登录成功-重定向，因为这里没有数据共享，同时练习使用会话跟踪

            HttpSession session = req.getSession();
            session.setAttribute("user",u);


            String contextPath = req.getContextPath();//获取虚拟路径
            res.sendRedirect(contextPath+"/servletSelectAll");
        }else
        {
            //失败
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,res);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
